package br.com.divulgaqui.filtro.seguranca;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Properties;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.com.divulgaqui.entity.Pessoa;

/**
 * Servlet Filter implementation class SegrurancaFilter
 */
@WebFilter(filterName="SegrurancaFilter",urlPatterns = {"/admin/*","/cliente/*","/cliente*","/admin*"})
public class SegrurancaFilter implements Filter {

	@SuppressWarnings("rawtypes")
	private HashMap urlPerfil;
	private final String login = "/divulgaqui/login"; 

	/**
	 * Default constructor.
	 */
	public SegrurancaFilter() {
	}

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		boolean ok = verificarAcesso((HttpServletRequest)request);
		if(!ok){
			((HttpServletResponse) response).sendRedirect(login);
		}else{
			chain.doFilter(request, response);
		}		
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public void init(FilterConfig fConfig) throws ServletException {
		urlPerfil = new HashMap();
		try {
			String file = this.getClass().getClassLoader()
					.getResource("access.properties").getPath();
			Properties properties = new Properties();
			properties.load(new FileInputStream(file));
			urlPerfil.putAll(properties);
		} catch (Exception e) {
			throw new ServletException(e);
		}
	}

	/**
	 * 
	 * @param request
	 * @return
	 */
	protected boolean verificarAcesso(HttpServletRequest request) {
		String url = request.getRequestURI().replaceAll(request.getContextPath(), "").trim();		
		while (url.length() > 0) {
			url = "/"+url.split("/")[1]+"/";
			String perfil = (String) urlPerfil.get(url);
			if (perfil != null) {
				Pessoa pessoa = (Pessoa) request.getSession().getAttribute("pessoa");
				return (pessoa != null && (pessoa.getPerfil().getNome().equals(perfil)));
			} else if (!url.equals("/")) {
				int index = url.lastIndexOf("/");
				if (index > -1) {
					url = url.substring(0, index);
				}
			} else {
				url = "";
			}
		}
		return true;
	}

}
